const BorrowModule = require("../database/borrow");
const BookModule = require("../database/book");

const DatabaseUtils = require("../utils/network");
const sequelize = require("../database/index");
const { convertUTCToLocal } = require("../utils/format");
const { fn } = require("sequelize/dist");

// 预约
async function subscribe(req, res, next) {
  // 查询是否有库存
  const result = await DatabaseUtils.changeNumber(req, res, next, BookModule, {
    searchParam: ["book_id"],
    fn(data) {
      // data.number = Number(data.number) + 1;
      // return data;
      if (data.number <= 0) {
        return false;
      }
      return data;
    },
  });
  if (!result) {
    res.status(400).json({ msg: "库存不足" });
    return false;
  }

  // 创建借阅记录
  DatabaseUtils.addRecord(req, res, next, BorrowModule);
  // 库存-1
  await DatabaseUtils.changeNumber(req, res, next, BookModule, {
    searchParam: ["book_id"],
    fn(data) {
      data.number = Number(data.number) - 1;
      return data;
    },
  });
}

// 取消预约
async function cancelSubscribe(req, res, next) {
  // 删除借阅记录
  DatabaseUtils.del(req, res, next, BorrowModule);
  // 库存+1
  await DatabaseUtils.changeNumber(req, res, next, BookModule, {
    searchParam: ["book_id"],
    fn(data) {
      data.number = Number(data.number) + 1;
      return data;
    },
  });
}

// 查询借阅情况
async function getBorrowRecord(req, res, next) {
  let { user_id, status } = req.query;
  status ? (status = "status=" + status) : (status = "1=1");

  // 获取书籍列表
  const [books] = await sequelize.query(
    `SELECT * from books WHERE book_id IN(SELECT book_id FROM borrows WHERE user_id='${user_id}' AND ${status})`
  );
  console.log({ books });

  // 获取借阅情况
  const result = await DatabaseUtils.getData(req, res, next, BorrowModule, {
    workMode: "return",
  });
  // console.log({ result });

  // 数据处理，并返回
  result.forEach((item) => {
    books.forEach((book) => {
      book.book_id == item.book_id ? Object.assign(book, item) : "";
    });
  });
  books.forEach((book) => {
    book.borrow_time = convertUTCToLocal(book.borrow_time);
    book.return_time = convertUTCToLocal(book.return_time);
    book.tag = book.tag.split("-");
  });
  // console.log({ books });

  // console.log({ books });
  res.status(200).json({
    msg: "查询成功",
    info: books,
  });
}

// 归还图书
async function deleteBook(req, res, next) {
  try {
    // 库存+1
    const result = await DatabaseUtils.changeNumber(
      req,
      res,
      next,
      BookModule,
      {
        searchParam: ["book_id"],
        fn(data) {
          data.number = Number(data.number) + 1;
          return data;
        },
      }
    );
    // 更改图书状态
    DatabaseUtils.alter(req, res, next, BorrowModule, {
      searchParam: ["book_id", "user_id"],
      alterParam: ["status"],
    });
  } catch (error) {
    console.log({ error });
  }
}

module.exports = {
  subscribe,
  getBorrowRecord,
  deleteBook,
  cancelSubscribe,
};
